const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https'),
      body = require('koa-bodyparser'),
      hq = require('./main.js'),
      gohttp = require('gohttp'),
      request = require('request'),
      check = require('./img_check.js');
      up = require('./uploadConfig.js')
const express = require('express');

const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}
app.use(body());
app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/test') {
          return "*"; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了 
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))



Date.prototype.Format = function(fmt) { //author: meizz 
    var o = {
                "M+": this.getMonth() + 1, //月份 
                "d+": this.getDate(), //日 
                "h+": this.getHours(), //小时 
                "m+": this.getMinutes(), //分 
                "s+": this.getSeconds(), //秒 
                "S": this.getMilliseconds() //毫秒 
            };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}


function time(date){
    t1=date;
    t2=new Date().getTime();
    t = t2 -t1;
    //console.log(t);
    if(t<60*1000) return '刚刚';
    else if(t<3600*1000){ 
        t=(t-t%60000)/60000;
        return t+'分钟前';
    }
    else if(t<24*3600*1000){
        t=(t-t%3600000)/3600000;
        return t+'小时前';
    }
    else if(t<365*24*3600*1000){
        t=(t-t%86400000)/86400000;
        return t+'天前';
    }
    else if(t>365*24*3600*1000){
        t=(t-t%31536000000)/31536000000;
        return t+'年前';
    }
}

//主页分享
router.post('/main/enjoy',async (ctx)=>{
  let {user_id, shop_id, title, text, addr, tags,
       food, top, judge, jwd } = ctx.request.body;
  let today = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
  let open_id = ctx.request.header.token;
  log(open_id)
  let arr = await hq.get_top(shop_id);
  await hq.insert_main(open_id,shop_id,title,text,today,addr,tags,food,top,0,jwd);
  if(arr.length!=0) {
    const score = (parseFloat(arr[0].num) * parseFloat(arr[0].score) + parseFloat(top) ) / ( parseFloat(arr[0].num) + 1);
    let brr = await hq.update_top(shop_id,score,arr[0].num);
  }
  let crr = await hq.get_main(today);
  log(crr)
  ctx.body = JSON.stringify(crr);
})

//图片检查
const multiparty = require('koa2-multiparty');
router.post('/main/imgcheck', multiparty(), async (ctx) =>{
  //console.log(ctx.req.files);
  const { files } = ctx.req;
  const stream = fs.createReadStream(files.file.path)
  const accesstoken = await check.getAccessToken() 
  const checkResult = await check.imgSecCheck(accesstoken, stream)
  const jsonResult = JSON.parse(checkResult)
  //console.log(jsonResult);
  if (jsonResult.errcode !== 0) {
    ctx.body = JSON.stringify('图片违规');
  } else {
    ctx.body = JSON.stringify('dnmdzql');
  }
})

//图片上传
router.post('/main/upload', up.upload.single('file'), async (ctx, next) => {
  const filename1 = '/public/upload/'+ctx.req.file.filename
  let id = ctx.request.header.id;
  let img = 'img'+(parseInt(ctx.request.header.index)+1);
  let size = ctx.request.header.size;
  if(img == 'img1'){
    await hq.insert_img(id,filename1,size);
  }else {
    await hq.update_img(id,img,filename1)
  }
  let arr = await hq.get_img(id);
  log(arr.length)
  ctx.body = JSON.stringify(arr.length)
});

router.get('/main/select_img', async (ctx)=>{
  let {id} = ctx.request.query
  let arr = await hq.get_img(id);
  log(arr);
  ctx.body = JSON.stringify(arr);
})
process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});

app.use(router.routes())
   .use(router.allowedMethods());
//app.listen(2227);


https.createServer(options,app.callback()).listen(2220);

